﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Lesson13_异步_服务端
{
    internal class ClientSocket
    {
        public Socket socket;
        public int clientID;
        private static int CLIENT_BEGIN_ID = 1;
        private byte[] cacheBytes = new byte[1024];
        private int cacheNum = 0;

        public ClientSocket(Socket socket)
        {
            this.clientID = CLIENT_BEGIN_ID++;
            this.socket = socket;

            //开始收消息
            this.socket.BeginReceive(cacheBytes, cacheNum, cacheBytes.Length, SocketFlags.None, RecviveCallBack, null);
        }

        private void RecviveCallBack(IAsyncResult result)
        {
            try
            {
                //返回值：收到了多少个字节
                int num = this.socket.EndReceive(result);
                //进行消息处理
                Console.WriteLine("[ClientSocket][RecviveCallBack] Msg:{0}", Encoding.UTF8.GetString(cacheBytes, 0, num));
                //继续接收消息
                if (this.socket.Connected)
                    this.socket.BeginReceive(cacheBytes, cacheNum, cacheBytes.Length, SocketFlags.None, RecviveCallBack, null);
            }
            catch (SocketException e)
            {
                Console.WriteLine("[ClientSocket][RecviveCallBack] error code:{0}", e.SocketErrorCode);
            }
        }

        public void Send(string msg)
        {
            if (!this.socket.Connected)
                return;
            byte[] bytes = Encoding.UTF8.GetBytes(msg);
            this.socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, SendCallBack, null);
        }

        private void SendCallBack(IAsyncResult result)
        {
            try
            {
                //返回值：发送了多少个字节
                int num = this.socket.EndSend(result);
                Console.WriteLine("[ClientSocket][SendCallBack] Success len:{0}", num);
            }
            catch (SocketException e)
            {
                Console.WriteLine("[ClientSocket][SendCallBack] error code:{0}", e.SocketErrorCode);
            }
        }
    }
}
